

var eventsMgr = require('eventsMgr');
var consts = require('consts');

var SoundsMgr = function () {
    // this.audioMusicID = -1;
    this.curMusicName = '';//当前目标音乐
}
var pro = SoundsMgr.prototype;
pro.initSounds = function(){
    eventsMgr.on(consts.EVENTS.PLAY_SOUND,this._playSound,this);
    eventsMgr.on(consts.EVENTS.PLAY_MUSIC,this._playMusic,this);
}
/**
 * 解析声音播放
 * @param data
 * @private
 */
pro._playSound = function(data){
    var target = data.target;
    if (!!target){
        this.playSoundEffect(target,function () {
            let next = data.next;
            if (next){
                eventsMgr.doEvent(next);
            }
        })
    }else{
        cc.warn('播放声音:',data);
    }
}
pro._playMusic = function(data){

    var target = data.target;
    if (!!target){
        this.playBackgroundMusic(target)
    }else{
        cc.warn('播放背景音乐:',data);
    }
}
pro.stopBackgroundMusic = function(){
    cc.log("音乐播放状态:"+cc.audioEngine.isMusicPlaying());
    if (cc.audioEngine.isMusicPlaying()){
        cc.audioEngine.stopMusic();
    }
}
/**
 *
 * @param fileName
 */
pro.playBackgroundMusic = function (fileName) {
    var self = this;//.audioMusicID;
    fileName = "sounds/"+fileName;
    self.stopBackgroundMusic();
    self.curMusicName = fileName;

    cc.loader.loadRes(fileName,cc.AudioClip,function (err, res) {
        cc.audioEngine.setMusicVolume(0.4);
        cc.audioEngine.playMusic(res,true);
    });
}
/**
 * 播放音效
 * @param fileName
 */
pro.playSoundEffectByName = function (fileName,callback) {
    var filePath = 'sounds/'+fileName;
    this.playSoundEffect(filePath,callback);
}
/**
 * 播放音效
 * @param pathName
 */
pro.playSoundEffect = function (pathName,callback) {
    var clip = cc.loader.getRes(pathName+'.mp3',cc.AudioClip);
    if (!!clip){
        let audioId = cc.audioEngine.playEffect(clip,false);
        cc.audioEngine.setFinishCallback(audioId,function () {
            if (callback){
                callback();
            }
        })
    }else{
        cc.loader.loadRes(pathName,cc.AudioClip,function (err, res) {
            if (!!err){
                cc.log(err);
            }else{
                let audioId = cc.audioEngine.playEffect(clip,false);
                cc.audioEngine.setFinishCallback(audioId,function () {
                    if (callback){
                        callback();
                    }
                })
            }
        });
    }
}
module.exports = new SoundsMgr();